<?php

namespace Registro\Common\Plugins;

use Phalcon\Acl;
use Phalcon\Events\Event;
use Phalcon\Mvc\User\Plugin;
use Phalcon\Mvc\Dispatcher;

/**
 * SecurityPlugin
 *
 * This is the security plugin which controls that users only have access to the modules they're assigned to
 */
class SecurityPlugin extends Plugin {

    /**
     * This action is executed before execute any action in the application
     *
     * @param Event $event
     * @param Dispatcher $dispatcher
     */
    public function beforeExecuteRoute( Event $event, Dispatcher $dispatcher )
    {
        $controller = $dispatcher->getControllerName();
        $action = $dispatcher->getActionName();

        // Only check permissions on private controllers
        if( $this->acl->isPrivate( $controller ) )
        {

            // Get the current identity
            $identity = $this->auth->getIdentity();

            // If there is no identity available the user is redirected to index/index
            if( !is_array( $identity ) )
            {
                $this->flash->notice( 'You don\'t have access to this module: private' );

                $dispatcher->forward( array(
                    'namespace' => 'Registro\Common\Controllers',
                    'controller' => 'exceptions',
                    'action' => 'show401'
                ) );
                return false;
            }

            if( $this->acl->isAllowed( $identity['profile']['profile_name'], $controller, $action ) != Acl::ALLOW )
            {
                $this->flash->notice( 'You don\'t have access to this module: ' . $controller . ':' . $action );

                $dispatcher->forward( array(
                    'namespace' => 'Registro\Common\Controllers',
                    'controller' => 'exceptions',
                    'action' => 'show401'
                ) );

                return false;
            }
        }

        //$auth = $this->session->get('auth');
//        $auth = $this->auth->getIdentity();
//
//        if( !$auth )
//        {
//            $role = 'Guest';
//        }
//        else
//        {
//            $role = 'User';
//        }
//
//        $controller = $dispatcher->getControllerName();
//        $action = $dispatcher->getActionName();
//
//        $acl = $this->acl->getAcl();
//
//        $allowed = $acl->isAllowed( $role, $controller, $action );
//
//        if( $allowed != Acl::ALLOW )
//        {
//            $this->flash->error( 'You don\'t have access to this module. Security Plugin: ' . $controller . ':' . $action );
//            $dispatcher->forward( array(
//                'namespace' => 'Registro\Common\Controllers',
//                'controller' => 'exceptions',
//                'action' => 'show401'
//            ) );
//
//            $this->session->destroy();
//            return false;
//        }
    }

}
